<script setup>
import {ref} from 'vue'
import {Message, DocumentChecked } from "@element-plus/icons-vue";
import {updataEmailService,sendVerificationCodeService} from '@/api/user'

const formModel=ref({
    newEmail: '',
    verification: ''
})

const rules = {
    newEmail: [
    { required: true, message: "请输入邮箱" ,trigger: "blur"},
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
  verification: [{ required: true, message: "请输入邮箱验证码" }],
};
const timer=ref()
const seconds=30
const currentSeconds=ref(seconds)
const form=ref()
const emailFormItem=ref()
//调接口发送邮箱验证码
const sendEmailCode= async ()=>{
    if(timer.value){
        return 
    }
    await emailFormItem.value.validate()
    const res=await sendVerificationCodeService(formModel.value.newEmail)
  console.log(res)
    timer.value=setInterval(() => {
        currentSeconds.value--
        if (currentSeconds.value === 0) {
          currentSeconds.value = seconds
          clearInterval(timer.value)
          timer.value = null
        }
      }, 1000)  
}

const updataEmail=async ()=>{
    await form.value.validate(); //进行所有表单项验证
    const res=await updataEmailService(formModel.value.newEmail,formModel.value.verification)
    console.log(res)
    ElMessage.success("邮箱修改成功");
}


</script>

<template>
    <div>
  <el-form label-position="left" :rules="rules" :model="formModel" label-width="auto" style="max-width: 600px">
    <el-form-item ref="emailFormItem" style="width: 310px;" prop="newEmail" label="邮箱">
      <el-input
        v-model="formModel.newEmail"
        placeholder="请输入新邮箱"
        :prefix-icon="Message"
      ></el-input>
    </el-form-item>

    <el-form-item prop="verification" label="邮箱验证码">
                <el-input
                  style="width: auto"
                  v-model="formModel.verification"
                  placeholder="请输邮箱验证码"
                  :prefix-icon="DocumentChecked"
                ></el-input>
                
                <el-button :disabled='currentSeconds != seconds' @click="sendEmailCode()"   style="margin-left: 30px" plain
                  >{{currentSeconds === seconds ? '获取邮箱验证码' : currentSeconds+'秒后重新获取'}}</el-button
                >
                
              </el-form-item>

              <el-form-item >
      <el-button type="primary" @click="updataEmail">提交</el-button>
      
    </el-form-item>
  </el-form>
</div>
</template>

<style scoped></style>
